package com.jamal2362.apktool.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.Deflater;

public class Zipper
{
    public static void zip(File[] files, String zipFile)
	{
        try
		{
			File[] allFiles = getAllFiles(files);
			int len = files[0].getParent().length() + 1;
            BufferedInputStream origin = null;
            FileOutputStream dest = new FileOutputStream(zipFile);
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
			out.setLevel(Deflater.BEST_COMPRESSION);
            byte data[] = new byte[2048];
            for (int i = 0; i < allFiles.length; i++)
			{
				String entryName = allFiles[i].getAbsolutePath().substring(len);
				if (allFiles[i].isDirectory())
				{
					if (!entryName.endsWith(File.separator))
						entryName += File.separator;
					ZipEntry entry = new ZipEntry(entryName);
					out.putNextEntry(entry);
					out.closeEntry();
					continue;
				}
				ZipEntry entry = new ZipEntry(entryName);
                out.putNextEntry(entry);
				FileInputStream fi = new FileInputStream(allFiles[i]);
                origin = new BufferedInputStream(fi, data.length);
                int count = 0;
                while ((count = origin.read(data)) != -1)
				{
                    out.write(data, 0, count);
                }
				out.closeEntry();
                origin.close();
            }
            out.finish();
            out.close();
        }
		catch (Exception e)
		{
            e.printStackTrace();
        }
    }

	private static File[] getAllFiles(File[] list)
	{
		List<File> res = getAllFilesList(list);
		File[] res3 = new File[res.size()];
		for (int i = 0; i < res.size(); i++)
		{
			res3[i] = res.get(i);
		}
		return res3;
	}

	private static List<File> getAllFilesList(File[] list)
	{
		List<File> res = new ArrayList<File>();
		if (list == null)
			return res;
		for (File file : list)
		{
			res.add(file);
			if (file.isDirectory())
			{
				res.addAll(getAllFilesList(file.listFiles()));
			}
		}
		return res;
	}
}
